using System.Collections.Generic;
using UnityEngine;

public class Inventory_Merchant : Inventory_Base
{
    public ItemListDataSO shopItemsData;

    private Inventory_Player playerInventory;
    [SerializeField] private int minShopAmount = 5;
    [SerializeField] private int maxShopAmount = 10;


    protected override void Awake()
    {
        base.Awake();
        UpdateStore();
    }

    public void SetInventoryPlayer(Inventory_Player playerInventory)
    {
        this.playerInventory = playerInventory;
    }

    public void UpdateStore()
    {
        itemList.Clear();
        List<Inventory_Item> possibleItemList = new();
        foreach (var itemData in shopItemsData.itemListData)
        {
            Inventory_Item itemToShop = new(itemData);

            int randomItemAmount = Random.Range(itemData.minStackSizeInShop, itemData.maxStackSizeInShop + 1);
            int finalItemAmount = Mathf.Clamp(randomItemAmount, 1, itemData.maxStackSize);
            itemToShop.stackSize = finalItemAmount;

            possibleItemList.Add(itemToShop);
        }

        int shopAmount = Random.Range(minShopAmount, maxShopAmount + 1);
        int finalAmount = Mathf.Clamp(shopAmount, 1, possibleItemList.Count);
        for (int i = 0; i < finalAmount; i++)
        {
            int randomIndex = Random.Range(0, possibleItemList.Count);
            var item = possibleItemList[randomIndex];
            if (CanAddItem(item))
            {
                itemList.Add(item);
                possibleItemList.Remove(item);
            }
        }
        OnTriggerUpdateUI();
    }

    public void TryBuyItem(Inventory_Item itemToBuy, bool buyFullStack)
    {
        int amountToBuy = buyFullStack ? itemToBuy.stackSize : 1;

        for (int i = 0; i < amountToBuy; i++)
        {
            if (playerInventory.gold < itemToBuy.price)
                return;
            
            Inventory_Item itemToAdd = new(itemToBuy.itemData);

            if (itemToBuy.itemData.itemType == ItemType.Material)
            {
                RemoveOneItemInOneSlot(itemToBuy);
                storage.TryAddItemToMaterialStorage(itemToAdd);
            }
            else
            {
                if (playerInventory.CanAddItem(itemToBuy))
                {
                    RemoveOneItemInOneSlot(itemToBuy);
                    playerInventory.AddItem(itemToAdd);
                }
                else return;
            }

            playerInventory.gold -= itemToBuy.price;
        }

        OnTriggerUpdateUI();
    }

    public void TrySellItem(Inventory_Item itemToBuy, bool buyFullStack)
    {
        int amountToSell = buyFullStack ? itemToBuy.stackSize : 1;

        for (int i = 0; i < amountToSell; i++)
        {
            playerInventory.gold += itemToBuy.sellPrice;
            playerInventory.RemoveOneItemInOneSlot(itemToBuy);
        }
        OnTriggerUpdateUI();
    }
}
